package com.vf.cloud.paas.app.agent.common.server.signalling.streamer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import com.vf.cloud.paas.app.agent.common.server.signalling.channel.StreamerChannelInitializer;
import com.vf.cloud.paas.common.service.IRedis;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.WriteBufferWaterMark;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class StreamerServer {
	
	@Autowired
	private IRedis redisImpl;

	@Value("${app.install.path}")
	private String installPath;
	@Value("${agent.signalling.streamerPort}")
	private int streamerPort;
	
	@Value("${agent.signalling.idleTimeout}")
	private int idleTimeout;

	@Value("${agent.aws.enabled}")
	private boolean enabled;
	
	@Value("${agent.aws.ip}")
	private String awsIp;

	@Value("${agent.aws.stun.port}")
	private int stunPort;

	@Value("${agent.aws.turn.port}")
	private int turnPort;

	@Value("${agent.aws.turn.username}")
	private String username;

	@Value("${agent.aws.turn.password}")
	private String password;

	@Value("${agent.aws.turn.localIp}")
	private String localIp;

	private EventLoopGroup boss;
	private EventLoopGroup work;
	private Channel channel;

	@Async
	public void run() {
		try {
			ServerBootstrap bootstrap = new ServerBootstrap();
			boss = new NioEventLoopGroup();
			work = new NioEventLoopGroup();

			log.info(">>>正在启动 --> StreamerServer:" + streamerPort);
			bootstrap.group(boss, work);
			bootstrap.channel(NioServerSocketChannel.class);
			bootstrap.option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(512 * 1024, 1024 * 1024));
			bootstrap.childHandler(
					new StreamerChannelInitializer(redisImpl,streamerPort,awsIp,enabled, stunPort, turnPort, username, password, localIp,idleTimeout));
			channel = bootstrap.bind(streamerPort).sync().channel();
			log.info(">>>启动成功 --> StreamerServer:" + streamerPort);
			if(channel!=null  && channel.closeFuture()!=null) {
				channel.closeFuture().sync();
			}
		} catch (Exception e) {
		} finally {
			work.shutdownGracefully();
			boss.shutdownGracefully();
			log.info(">>>已关闭 --> StreamerServer:" + streamerPort);
		}
	}

	public void destroy() {
		if(channel!=null) {
			channel.close();
		}
		work.shutdownGracefully();
		boss.shutdownGracefully();
	}

}
